package com.sky.service.impl;

import com.sky.constant.DefaultImageConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.AdminConstant;
import com.sky.dto.MyselfLoginDTO;
import com.sky.dto.MyselfRegisterDTO;
import com.sky.entity.Myself;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.exception.RegisterFailedException;
import com.sky.mapper.MyselfMapper;
import com.sky.service.MyselfService;
import com.sky.utils.AliOssUtil;
import com.sky.vo.AiMyselfInfoVO;
import com.sky.vo.MyselfInfoVO;
import com.sky.vo.MyselfRegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@Slf4j
public class  MyselfServiceImpl implements MyselfService {


    private final MyselfMapper myselfMapper;


    private final AliOssUtil aliOssUtil;

    private PasswordEncoder passwordEncoder;  // 注入 BCrypt 编码器

    @Autowired
    public MyselfServiceImpl(MyselfMapper myselfMapper, AliOssUtil aliOssUtil, PasswordEncoder passwordEncoder) {
        this.myselfMapper = myselfMapper;
        this.aliOssUtil = aliOssUtil;
        this.passwordEncoder = passwordEncoder;
    }


    /**
     * 登录
     */
    @Override
    public Myself login(MyselfLoginDTO myselfLoginDTO) {

        //获取用户名和密码
        String username = myselfLoginDTO.getUsername();
        String password = myselfLoginDTO.getPassword();

        //根据用户名查询数据库
        Myself myself = myselfMapper.getByUsername(username);

        //处理异常，账号不存在
        if (myself == null) {
            //账号不存在
            log.warn("账号不存在：{}", username);
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }


        //比对BCrypt加密后的密码
        if (!passwordEncoder.matches(password, myself.getPassword())) {
            //密码错误
            log.warn("密码错误：{}", username);
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //返回实体对象
        return myself;
    }

    /**
     * 注册
     */
    @Override
    @Transactional
    public MyselfRegisterVO register(MyselfRegisterDTO myselfRegisterDTO) {
        //1. 检查用户名是否存在
        Myself myself = myselfMapper.getByUsername(myselfRegisterDTO.getUsername());

        if (myself != null) {
            //用户名已存在
            log.warn("用户名已存在：{}", myselfRegisterDTO.getUsername());
            throw new RegisterFailedException(MessageConstant.USERNAME_EXISTS);
        }

        // 使用 BCrypt 编码器加密密码
        String encryptedPassword = passwordEncoder.encode(myselfRegisterDTO.getPassword());


        //创建插入用户数据
        Myself insertMyself = Myself.builder()
                .name(myselfRegisterDTO.getName())
                .username(myselfRegisterDTO.getUsername())
                .password(myselfRegisterDTO.getPassword())
                .phone(myselfRegisterDTO.getPhone())
                .qq(myselfRegisterDTO.getQq())
                .wechat(myselfRegisterDTO.getWechat())
                .sex(myselfRegisterDTO.getSex())
                .password(encryptedPassword)
                .build();

        //上传头像到OSS
        MultipartFile file = myselfRegisterDTO.getAvatar();
        if (file == null) {
            //设置默认头像
           if (insertMyself.getSex().equals(AdminConstant.SEX_MAN)) {
               insertMyself.setAvatar(DefaultImageConstant.MAN);
           }else
               insertMyself.setAvatar(DefaultImageConstant.WOMAN);
        }else {
            try {
                String avatar = aliOssUtil.upload(file.getBytes(), file.getOriginalFilename());
                //设置头像地址
                insertMyself.setAvatar(avatar);
            } catch (IOException e) {
                log.error("上传头像到OSS失败：{}", e.getMessage());
                throw new RegisterFailedException(MessageConstant.UPLOAD_FAILED);
            }
        }



        //设定用户权限
        insertMyself.setRoot(AdminConstant.DEFAULT_ROOT);

        //4. 插入数据库
        myselfMapper.insertUser(insertMyself);

        //5. 返回VO
        MyselfRegisterVO myselfRegisterVO = new MyselfRegisterVO();
        BeanUtils.copyProperties(insertMyself, myselfRegisterVO);
        //清空密码
        myselfRegisterVO.setPassword(null);


        return myselfRegisterVO;
    }

    /**
     * 博客首页直接获取我的信息
     */
    @Override
    public MyselfInfoVO getMyInfo() {

        Myself myself = myselfMapper.getByUsername(AdminConstant.MY_NAME);

        MyselfInfoVO myselfInfoVO = new MyselfInfoVO();
        if (myself == null) {
            //用户不存在
            log.warn("用户不存在：{}", AdminConstant.MY_NAME);
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        BeanUtils.copyProperties(myself,myselfInfoVO);
        return myselfInfoVO;
    }


    /**
     * AI大模型调用接口方法查找作者信息
     */
    @Override
    public AiMyselfInfoVO findMyselfInfo() {
        Myself myself = myselfMapper.findMyselfInfo();
        return AiMyselfInfoVO.builder()
                .name(myself.getName())
                .phone(myself.getPhone())
                .qq(myself.getQq())
                .wechat(myself.getWechat())
                .build();
    }
}
